#include "yschartview.h"
#include <QVBoxLayout>
#include <QScreen>
#include <QGuiApplication>
#include <QTimer>
#include <mainwindow.h>

YSChartView::YSChartView(QWidget *parent)
    : QWidget(parent)
    , maxPoints(50)
    , currentIndex(0)
    , baseWidth(300)
    , baseHeight(200)
{
    setupChart();
    // 创建布局
    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->addWidget(chartView);
    layout->setContentsMargins(0, 0, 0, 0);
    setLayout(layout);
    
    // 调整大小
    adjustSizeByScreen();
}

void YSChartView::setBaseSize(int width, int height)
{
    // 计算新的按钮大小
    baseWidth = width ;
    baseHeight = height;
    adjustSizeByScreen();
}

void YSChartView::adjustSizeByScreen()
{
    // 设置最小尺寸
    setFixedSize(baseWidth, baseHeight);
    
    // 调整图表视图的大小
    chartView->setFixedSize(baseWidth, baseHeight);
    // 调整坐标轴字体
    QFont axisFont = axisX->labelsFont();
    axisFont.setPixelSize(qRound(15* g_xScale));    // 基准字体大小为9
    axisX->setLabelsFont(axisFont);
    axisY->setLabelsFont(axisFont);
    
    // 更新标题样式
    updateTitleStyle();
}

void YSChartView::setupChart()
{
    // 创建图表
    chart = new QChart();
    
    // 隐藏默认标题
    chart->setTitle("");
    
    // 将图例移到底部并隐藏
    chart->legend()->setVisible(false);
    
    // 设置背景为不透明，使用与主窗口相同的颜色
    chart->setBackgroundVisible(true);
    chart->setBackgroundBrush(QBrush(QColor("#2E2F31")));
    chart->setPlotAreaBackgroundVisible(true);
    chart->setPlotAreaBackgroundBrush(QBrush(QColor("#2E2F31")));
    
    // 创建坐标轴
    axisX = new QValueAxis;
    axisY = new QValueAxis;
    
    axisX->setRange(0, maxPoints);
    axisY->setRange(-180, 180);
    
    // 设置网格线颜色为深灰色
    axisX->setGridLineColor(QColor("#4C4D51"));
    axisY->setGridLineColor(QColor("#4C4D51"));
    
    // 设置轴线和标签颜色为深灰色
    QPen axisPen(QColor("#4C4D51"));
    axisPen.setWidth(1);  // 设置轴线宽度为1像素
    axisX->setLinePen(axisPen);
    axisY->setLinePen(axisPen);
    
    // 设置标签颜色为深灰色
    axisX->setLabelsBrush(QBrush(QColor("#4C4D51")));
    axisY->setLabelsBrush(QBrush(QColor("#4C4D51")));
    axisX->setLabelFormat("%.1f"); // 设置Y轴标签格式，保留一位小数
    axisY->setLabelFormat("%.1f"); // 设置Y轴标签格式，保留一位小数
    // 设置图表边距，为底部标题留出空间
    chart->setMargins(QMargins(10*g_xScale, 10*g_xScale, 10*g_xScale, 30*g_xScale));
    
    chart->addAxis(axisX, Qt::AlignBottom);
    chart->addAxis(axisY, Qt::AlignLeft);
    
    // 创建图表视图
    chartView = new QChartView(chart);
    chartView->resize(width(),height());
    chartView->setRenderHint(QPainter::Antialiasing);
    // 设置图表视图背景
    chartView->setBackgroundBrush(QBrush(QColor("#2E2F31")));
    // 创建标题标签
    titleLabel = new YSLabel(chartView);
    titleLabel->setAlignment(Qt::AlignCenter);
    titleLabel->setStyleSheet("QLabel { color: #CCCCCC; background: transparent; }");
    titleLabel->setFont(QFont("微软雅黑", 20*g_xScale));
}

void YSChartView::clearData()
{
    for(QLineSeries *series : jointSeries) {
        series->clear();
    }
    currentIndex = 0;
    axisX->setRange(0, maxPoints);
}

void YSChartView::setRange(double yMin, double yMax)
{
    axisY->setRange(yMin, yMax);
}

void YSChartView::setMaxPoints(int points)
{
    maxPoints = points;
    axisX->setRange(0, maxPoints);
}

void YSChartView::setChartTitle(const QString& title)
{
    if(titleLabel) {
        titleLabel->setText(title);
        // 调整标签位置
        QTimer::singleShot(0, this, [this]() {
            int x = (chartView->width() - titleLabel->width()) / 2;
            titleLabel->move(x, chartView->height() - titleLabel->height() - 5);
        });
    }
}

void YSChartView::setTitleColor(const QColor& color)
{
    chart->setTitleBrush(QBrush(color));
}

void YSChartView::updateTitleStyle()
{
    // 获取当前缩放比例
    QFont titleFont = titleLabel->font();
    titleFont.setPixelSize(qRound(22 * g_xScale));
    titleLabel->setFont(titleFont);
}

void YSChartView::setLineVisible(int index, bool visible)
{
    if(index >= 0 && index < jointSeries.size()) {
        jointSeries[index]->setVisible(visible);
    }
}

bool YSChartView::isLineVisible(int index) const
{
    if(index >= 0 && index < jointSeries.size()) {
        return jointSeries[index]->isVisible();
    }
    return false;
}

void YSChartView::initializeLines(const QVector<LineConfig>& configs)
{
    clearSeries();
    initializeSeries(configs);
    currentIndex=0;
}

void YSChartView::clearSeries()
{
    // 清除现有的所有折线
    for(QLineSeries* series : jointSeries) {
        chart->removeSeries(series);
        delete series;
    }
    jointSeries.clear();
}

void YSChartView::initializeSeries(const QVector<LineConfig>& configs)
{
    // 创建新的折线
    for(int i = 0; i < configs.size(); i++) {
        QLineSeries *series = new QLineSeries();
        series->setName(configs[i].name);
        QPen pen(configs[i].color);
        pen.setWidth(1);  // 线宽为1像素
        series->setPen(pen);
        series->setVisible(configs[i].visible);
        
        chart->addSeries(series);
        series->attachAxis(axisX);
        series->attachAxis(axisY);
        
        jointSeries.append(series);
    }
}

void YSChartView::updateLineConfig(int index, const LineConfig& config)
{
    if(index >= 0 && index < jointSeries.size()) {
        QLineSeries* series = jointSeries[index];
        series->setName(config.name);
        
        QPen pen = series->pen();
        pen.setColor(config.color);
        series->setPen(pen);
        
        series->setVisible(config.visible);
    }
}

void YSChartView::updateLineData(int lineIndex, double value)
{
    if(lineIndex < 0 || lineIndex >= jointSeries.size())
        return;

    QLineSeries *series = jointSeries[lineIndex];
    
    // 添加新数据点
    series->append(currentIndex, value);
    
    // 如果超过最大点数，删除最早的点
    if(series->count() > maxPoints) {
        QList<QPointF> points = series->points();
        points.removeFirst();
        series->replace(points);
    }

    // 更新X轴范围
    if(currentIndex >= maxPoints) {
        axisX->setRange(currentIndex - maxPoints + 1, currentIndex/* + 1*/);
    }
}

void YSChartView::updateAllLines(const QVector<float>& values)
{
    if(values.size() != jointSeries.size())
        return;

    for(int i = 0; i < values.size(); i++) {
        updateLineData(i, values[i]);
    }
    currentIndex++;
}

void YSChartView::setLegendVisible(bool visible)
{
    chart->legend()->setVisible(visible);
}

float YSChartView::getMaxRange()
{
    return axisY->max();
}

float YSChartView::getMinRange()
{
    return axisY->min();
}

void YSChartView::resizeEvent(QResizeEvent* event)
{
    QWidget::resizeEvent(event);
    // 在大小改变时重新调整标题位置
    if(titleLabel) {
        int x = (chartView->width() - titleLabel->width()) / 2;
        titleLabel->move(x, chartView->height() - titleLabel->height() - 5);
    }
}

YSChartView::~YSChartView()
{
    delete chart;
} 
